<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>下拉列对象</title>
    <script>
        function f1(){
            let s1 = document.getElementById("s1");
            // 获取该下拉列对象中所有的选项所表示的Option对象数组
            let ops = s1.options;
            console.log(ops);
            for(let i = 0; i < ops.length; i++){
                console.log("文本值:"+ops[i].text);
                console.log("服务器值:"+ops[i].value);
            }
            // 获取下拉列中选中的选项的索引号
            let index = s1.selectedIndex;
            // 取出选中的选项
            let op = ops[index];
            console.log("当前所选的选项的文本值为:"+op.text+",服务器值为:"+op.value);
        }
        function f2(){
            let s1 = document.getElementById("s1");
            // let op = s1.options[s1.selectedIndex];
            // 简写方式
            let op = s1[s1.selectedIndex];
            console.log("当前所选的选项的文本值为:"+op.text+",服务器值为:"+op.value);
        }
        function f3(){
            let inText = document.getElementById("inText").value;
            let inValue = document.getElementById("inValue").value;
            let op = document.createElement("option");
            let opText = document.createTextNode(inText);
            op.appendChild(opText);
            op.value = inValue;
            let s1 = document.getElementById("s1");
            s1.appendChild(op);
        }

        function f4(){
            // 在JS中提供了Option对象的构造方法
            // new Option(文本值,服务器值)
            let inText = document.getElementById("inText").value;
            let inValue = document.getElementById("inValue").value;
            // let op = new Option(inText,inValue);
            // JS数组元素的长度是可变的
            // 只要在当前数组元素的末尾的后一位赋值,则数组扩充一个元素
            // 当DOM元素的内容发生变化之后,与之对应的HTML元素会随之改变
            let s1 = document.getElementById("s1");
            // s1[s1.length] = op;
            s1[s1.length] = new Option(inText,inValue);
        }

        function f5(){
            let s1 = document.getElementById("s1");
            let inText = document.getElementById("inText").value;
            let inValue = document.getElementById("inValue").value;
            s1[s1.selectedIndex] = new Option(inText,inValue);
        }

        function f6(){
            let s1 = document.getElementById("s1");
            s1[s1.selectedIndex] = null;
        }

        function f7(){
            let s1 = document.getElementById("s1");
            s1.length = 1;
        }
    </script>
</head>
<body>
文本值:<input type="text" id="inText"><br>
服务器值:<input type="text" id="inValue"><br>
<button onclick="f1()">测试</button>
<button onclick="f3()">添加</button>
<button onclick="f4()">添加</button>
<button onclick="f5()">修改选中项</button>
<button onclick="f6()">删除选中项</button>
<button onclick="f7()">清空选项</button>
<hr>
<select id="s1" onchange="f2()">
    <option value="-1">请选择</option>
    <option value="1">aaa</option>
    <option value="2">bbb</option>
    <option value="3">ccc</option>
</select>
</body>
</html>